package org.jeecg.common.util.wx;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

@Slf4j
public class WeiXinUtil {
    private static String appid;
    private static String appSecret;

    public static String getAppid() {
        return appid;
    }

    public static void setAppid(String appid) {
        WeiXinUtil.appid = appid;
    }

    public static String getAppSecret() {
        return appSecret;
    }

    public static void setAppSecret(String appSecret) {
        WeiXinUtil.appSecret = appSecret;
    }

    /**
     * 获取公众号token
     * @return
     * @throws MalformedURLException
     * @throws IOException
     * @throws ProtocolException
     */
    public static String getWxAppToken() throws MalformedURLException, IOException, ProtocolException {
        String path = " https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
        URL url = new URL(path + "&appid=" + appid + "&secret=" + appSecret);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        InputStream in = connection.getInputStream();
        byte[] b = new byte[100];
        int len = -1;
        StringBuffer sb = new StringBuffer();
        while ((len = in.read(b)) != -1) {
            sb.append(new String(b, 0, len));
        }
        in.close();
        return sb.toString();
    }

    public static void main(String[] args) {
        try {
            log.info("地址为：{}", getWxAppToken());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
